<template>
  <div class="pie-container" ref="mileage"></div>
</template>
<script>
import { EleResize } from "@/utils/resize/index.js";
let mileageEcharts = null;
let flag = false;
export default {
  props: {
    pieData: {
      type: Array,
      required: true,
    },
    unit: {
      type: String,
    },
  },
  data() {
    return {
      mileageEcharts: "", //行驶里程分布echarts
      newPieData: [],
      option: "",
      startCharts: null,
    };
  },
  watch: {
    pieData: {
      handler(newData, oldData) {
        this.newPieData = newData;
        if (this.newPieData && this.newPieData.length > 0) {
          this.$nextTick(() => {
            this.pie();
          });
        }
      },
      immediate: true,
      deep: true, // 如果是对象要深度监听
    },
  },
  methods: {
    pie() {
      this.$nextTick(() => {
        // var flag = true; // 为了做判断：当鼠标移动上去的时候，自动高亮就被取消
        let _this = this;
        let index = 0;
        let isSet = false;
        // if (this.startCharts) {
        //   mileageEcharts.dispose();
        //   mileageEcharts = null;
        // }

        mileageEcharts = this.$echarts.init(this.$refs.mileage);
        mileageEcharts.dispose();
        mileageEcharts = this.$echarts.init(this.$refs.mileage);
        mileageEcharts.clear();
        mileageEcharts.resize();
        const colorList = [
          "#FCBA62",
          "#00FFF0",
          "#1d8cff",
          "#00ff00",
          "#ba6eff",
        ];
        const sum = this.newPieData.reduce((per, cur) => per + cur.value, 0);
        const gap = (1 * sum) / 100;
        const pieData1 = [];
        for (let i = 0; i < this.newPieData.length; i++) {
          pieData1.push({
            ...this.newPieData[i],
            itemStyle: {
              // shadowColor: colorList[i],
              // shadowBlur: 10,
              // // shadowOffsetY: 2,
              // shadowOffsetX: 0,
              // borderColor: colorList[i],
              borderWidth: 2,
            },
          });
        }
        let option = {
          animation: true,
          grid: {
            width: "auto",
            height: "auto",
          },
          left: "60%",
          right: "10%",
          top: "center",
          // right: "center",
          bottom: "center",
          backgroundColor: "rgba(0,0,0,0)",
          title: [
            {
              text: "",
              left: "30%",
              top: "45%",
              textAlign: "center",
              textStyle: {
                fontSize: "16%",
                fontWeight: "400",
                color: "#fff",
                textAlign: "center",
                textShadowColor: "#000",
                textShadowBlur: "1",
                textShadowOffsetX: 1,
                textShadowOffsetY: 1,
              },
            },
          ],
          legend: {
            icon: "circle",
            origin: "horizontal",
            left: "68%",   //右边数据展示位置
            right: "10%",
            top: "top",
            align: "left",
            // orient: 'vertical',
            type: "scroll", // 数据过多时，分页显示
            scrollDataIndex: 0,// 指定一页翻五个
            itemWidth: 0,
            itemHeight: 12,
            shadowBlur: 5,
            shadowOffsetY: 0,
            shadowOffsetX: 0,
            itemGap: 20,
            selectedMode: false,
            textStyle: {
              color: "#D8DDE3",
              rich: {
                name: {
                  width: "500",
                  align: "left",
                  fontSize: "14%",
                  color: "#D8DDE3",
                },
              },
            },
            formatter: (name) => {
              const item = this.newPieData.find((i) => {
                // console.log('139',item)
                // console.log('140',i)
                return i.name === name;
              });
              return "{name|" + name +"}";
            },
          },
          color: colorList,
          series: [
            {
              type: "pie",
              z: 4,
              left: "0%",
              avoidLabelOverlap: false,
              radius: ["50%", "70%"],
              center: ["30%", "50%"],
              label: {
                show: false,
                position: "outside",
              },
              labelLine: {
                length: 14,
                length2: 20,
                maxSurfaceAngle: 80,
              },
              emphasis: {
                label: {
                  show: true,
                  rich: {
                    name: {
                      verticalAlign: "top",
                      fontSize: "16%",
                      color: "#fff",
                      lineHeight: 20,
                      textShadowColor: "#000",
                      textShadowBlur: 3,
                    },
                  },
                  // formatter: "{b} {c} \n\n",
                  formatter: (item) => {
                    let p = "";
                    if (item.value > 0) {
                      p = ((item.value / sum) * 100).toFixed(1) + "%";
                    } else {
                      p = "0%";
                    }
                    return "{name|" + item.name + "  " + p + "}";
                  },
                  padding: [0, -100],
                  alignTo: "labelLine",
                  minMargin: 5,
                  edgeDistance: 10,
                  lineHeight: 10,
                },
              },
              data: pieData1,
              tooltip: {
                show: true,
                trigger: "item",
              },
            },
            {
              name: "外边框",
              type: "pie",
              clockWise: false, //顺时加载
              hoverAnimation: false, //鼠标移入变大
              center: ["30%", "50%"],
              radius: ["88%", "88%"],
              label: {
                normal: {
                  show: false,
                },
              },
              data: [
                {
                  value: 9,
                  name: "",
                  itemStyle: {
                    normal: {
                      borderWidth: 2,
                      borderColor: "#0b5263",
                      shadowBlur: 10,
                      shadowColor: 'rgb(76,192,218)',
                    },
                  },
                },
              ],
            },
          ],
        };
        // 改变屏幕大小图表重新加载
        let resizeDiv = this.$refs.mileage; // 这个是渲染echarts的div
        let listener = () => {
          mileageEcharts.resize();
        };
        EleResize.on(resizeDiv, listener);
        this.option = option;
        option && mileageEcharts.setOption(option, true);

        // 鼠标事件
        let pieChart = mileageEcharts;
        //鼠标移出之后，恢复自动高亮
        pieChart.on("mouseout", function (param) {
          if (!isSet) {
            clearInterval(_this.startCharts);
            _this.startCharts = setInterval(chartHover, 2000);
            flag = true;
          }
        });

        echart.on("legendscroll", params => {
          // 阻止冒泡
          event.stopPropagation();
          // 滚动事件派发 --(注意这是一个死循环)
          echart.dispatchAction({
            type: "legendScroll",// params.type的是全小写事件名, 无法派发成功
            scrollDataIndex: params.scrollDataIndex + 1,// 目前我的是一页5条数据,而翻页的scrollDataIndex只有4条, 看百度官方给的命名是索引的意思, 实际上是条数(长度)了, 应该是echart的Bug!
            legendId: params.legendId
          });
        });
        //自动高亮显示
        var chartHover = function () {
          var dataLen = option.series[0].data.length;
          // 取消之前高亮的图形
          pieChart.dispatchAction({
            type: "downplay",
            seriesIndex: 0,
            dataIndex: index,
          });
          index = (index + 1) % dataLen;
          // 高亮当前图形
          pieChart.dispatchAction({
            type: "highlight",
            seriesIndex: 0,
            dataIndex: index,
          });
          if (option.series[0].data[index].value > 0) {
            option.title[0].text =
              ((option.series[0].data[index].value / sum) * 100).toFixed(1) +
              "%";
          } else {
            option.title[0].text = "0%";
          }
          pieChart.setOption(option, true);
          // 显示 tooltip
          pieChart.dispatchAction({
            type: "showTip",
            seriesIndex: 0,
            dataIndex: index,
          });
        };
        if (!_this.startCharts) {
          _this.startCharts = setInterval(chartHover, 3000);
        } else {
          clearInterval(_this.startCharts);
          _this.startCharts = setInterval(chartHover, 3000);
        }

        // 鼠标移动上去的时候的高亮动画
        pieChart.on("mouseover", function (param) {
          flag = false;
          isSet = false;
          clearInterval(_this.startCharts);
          //取消之前高亮图形
          pieChart.dispatchAction({
            type: "downplay",
            seriesIndex: 0,
            dataIndex: index,
          });
          index = param.dataIndex;
          //**解决文章所述问题**// //记录上一次选中值重新进入时取消高亮
          //高亮当前图形
          pieChart.dispatchAction({
            type: "highlight",
            seriesIndex: 0,
            dataIndex: param.dataIndex,
          });
          //显示tooltip
          pieChart.dispatchAction({
            type: "showTip",
            seriesIndex: 0,
            dataIndex: param.dataIndex,
          });
          if (option.series[0].data[index].value > 0) {
            option.title[0].text =
              ((option.series[0].data[index].value / sum) * 100).toFixed(1) +
              "%";
          } else {
            option.title[0].text = "0%";
          }
          pieChart.setOption(option, true);
        });
        // 先执行一遍自适应窗口
        mileageEcharts.resize();
      });
    },
  },
  beforeDestroy() {
    if (mileageEcharts) {
      mileageEcharts.dispose();
      mileageEcharts = null;
    }
  },
};
</script>
<style lang="scss" scoped>
.pie-container {
  width: 100%;
  height: 100%;
}
</style>
